package com.example.demo.utils;

import net.sf.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class Utils {
    public static void savecokie(String url, String savename) throws Exception {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.chrome.driver", "D:\\ChromeDriver\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.default_directory", "D:\\");
        options.setExperimentalOption("prefs", prefs);
        ChromeDriver webDriver = new ChromeDriver(options);
        webDriver.get(url); //
        Scanner scanner = new Scanner(System.in);
        scanner.next();
        Set<Cookie> cookies = webDriver.manage().getCookies();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\\cookie\\" + savename));
        objectOutputStream.writeObject(cookies);
    }

    public static void read(WebDriver webDriver, String path) throws Exception {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\cookie\\" + path));
        HashSet<Cookie> cookies = (HashSet<Cookie>) objectInputStream.readObject();
        webDriver.manage().deleteAllCookies();
        for (Cookie cookie : cookies) {
            webDriver.manage().addCookie(cookie);
        }
        // 与浏览器同步非常重要，必须等待浏览器加载完毕
        webDriver.navigate().refresh();
        webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    public static WebElement avoidCsselementnotfindexception(WebDriver webDriver, String csspath) throws Exception {
        while (true) {
            try {
                WebElement element = webDriver.findElement(By.cssSelector(csspath));
                return element;
            } catch (Exception e) {
                System.out.println("页面没找到元素,等待0.5秒");
                Thread.sleep(500);
            }

        }
    }

    public static WebElement avoidXpathelementnotfindexception(WebDriver webDriver, String xpath) throws Exception {
        while (true) {
            try {
                WebElement element = webDriver.findElement(By.xpath(xpath));
                return element;
            } catch (Exception e) {
                System.out.println("页面没找到元素,等待0.5秒");
                Thread.sleep(500);
            }

        }
    }

    public static Set<Cookie> read(String path) throws Exception {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\cookie\\" + path));
        HashSet<Cookie> cookies = (HashSet<Cookie>) objectInputStream.readObject();
        return cookies;
    }

    public static void Bilisendmessage() throws Exception {
        Connection connect = Jsoup.connect("https://api.bilibili.com/x/v2/reply/add");
        Map<String, String> header = new HashMap<String, String>();
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        header.put("Referer", "https://www.bilibili.com/video/BV13W411c7Yf?from=search&seid=14945655003133214162");
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        header.put("Origin", "https://www.bilibili.com");

        // 带参数开始
        Set<Cookie> read = Utils.read("bilixiao.txt");
        connect.headers(header);
        connect.cookie("Cookie", "sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; bp_t_offset_619772228=405164167916667135; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; PVID=10; bp_video_offset_619772228=409109640839843003");

        connect.data("oid", "409561604543791320");
        connect.data("type", "1");
        connect.data("message", "niu a");
        connect.data("plat", "1");
        connect.data("jsonp", "jsonp");
        connect.data("csrf", "2d1cd64f8d95d254d3dc44077a7df701");
        // 带参数结束
        Document document = connect.ignoreContentType(true).post();
    }

    public static void weibosendmessage() throws Exception {
        Connection connect = Jsoup.connect("https://weibo.com/aj/v6/comment/add");
        Map<String, String> header = new HashMap<String, String>();
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        header.put("Referer", "https://weibo.com/p/1005056603924493/home");
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        header.put("Origin", "https://weibo.com");
        connect.headers(header);
        connect.cookie("Cookie", "SINAGLOBAL=375533428638.6902.1594006608491; un=17549206538; wvr=6; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5l7FO6-yTrzN17umw3RE0z5JpX5KMhUgL.Foqcehe4eoBX1Ke2dJLoIEQLxK-L12qL1K2LxKML1KqLB-qLxKML1-2L1hB4eFH8SC-4eF-RxK-RShzt; wb_view_log_6603924493=1920*10801; ALF=1625640194; SSOLoginState=1594104199; SCF=AqtP3CQJ3qgaV_qFnl2dppBgju5G1wOIodAsk7mkGfFvZ1DCOD7V2ZJAHr4-dr95inQLHd6FUkwQ1ka40ejj_4A.; SUB=_2A25yAGnYDeRhGeBI61EY8irIwj-IHXVRdNwQrDV8PUNbmtAKLVrBkW9NRqbvqBo6Bh7_h6Ij0xGucuiz88HSN0Kg; SUHB=0JvgHwyX8Yg0Jy; Ugrow-G0=cf25a00b541269674d0feadd72dce35f; YF-V5-G0=9717632f62066ddd544bf04f733ad50a; _s_tentry=login.sina.com.cn; UOR=,,login.sina.com.cn; Apache=2505453532546.942.1594104218852; ULV=1594104218901:9:9:9:2505453532546.942.1594104218852:1594088229313; YF-V-WEIBO-G0=b09171a17b2b5a470c42e2f713edace0; YF-Page-G0=20a0c65c6e2ee949c1f78305a122073b|1594105190|1594105311; webim_unReadCount=%7B%22time%22%3A1594105369075%2C%22dm_pub_total%22%3A0%2C%22chat_group_client%22%3A0%2C%22chat_group_notice%22%3A0%2C%22allcountNum%22%3A0%2C%22msgbox%22%3A0%7D");

        connect.data("mid", "4524068012941734");
        connect.data("uid", "6603924493");
        connect.data("content", "niu6");

        // 带参数结束
        Document document = connect.ignoreContentType(true).post();
        System.out.println(document.title());
    }

    //还未完成
    public static void tengxunbosendmessage() throws Exception {
        Document document = Jsoup.connect("https://pacaio.match.qq.com/irs/rcd?cid=137&token=d0f13d594edfc180f5bf6b845456f3ea&id=&ext=top&page=0&expIds=&callback=__jp1").ignoreContentType(true).get();
        Element body = document.body();
        String text = body.text();
        int i = text.indexOf("(");
        String substring = text.substring(i + 1, text.length() - 1);
        JSONObject jsonObject = JSONObject.fromObject(substring);
        System.out.println(jsonObject);
    }

    //解析get请求返回的数据
    public static JSONObject getdatalist(String url) throws Exception {
        Document document = Jsoup.connect(url).ignoreContentType(true).get();
        Element body = document.body();
        String text = body.text();
        JSONObject jsonObject = JSONObject.fromObject(text);
        return jsonObject;
    }

    //给定url,header,data,cookie,发送post请求
    public static void postrequest(String url, Map<String, String> header, Map<String, String> data, String cookie) throws IOException {
        Connection connect = Jsoup.connect(url);
        connect.headers(header);
        connect.cookie("Cookie", cookie);
        connect.data(data);
        // 带参数结束
        Document document = connect.ignoreContentType(true).post();
    }


    //把请求头或请求体里的内容变成代码
    public static void getMap(String kaitou, String url) {
        String headers = url;
        String[] split = headers.split("\n");
        HashMap<String, String> map = new HashMap<>();
        for (String s1 : split) {
            //再以:分离
            String[] split1 = s1.split(": ");
            String s = split1[0].replaceAll(":", "");
            System.out.println(kaitou + "(" + "\"" + s + "\"" + "," + "\"" + split1[1] + "\"" + ")" + ";");
        }
    }


    //b站直播间发送弹幕
    public static void sendzhiboMessage(String roomid) throws Exception {
        String[] s = {"老sm", "嘿嘿"};
        for (int i = 0; i < s.length; i++) {
            Map<String, String> header = new HashMap<String, String>();
            HashMap<String, String> data = new HashMap<>();
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
            header.put("Referer", "https://live.bilibili.com/" + roomid);
            header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            header.put("Origin", "https://live.bilibili.com");
            data.put("roomid", roomid);
            data.put("msg", s[i]);
            data.put("csrf_token", "2d1cd64f8d95d254d3dc44077a7df701");
            data.put("csrf", "2d1cd64f8d95d254d3dc44077a7df701");
            data.put("color", "16711680");
            data.put("fontsize", "50");
            data.put("mode", "1");
            data.put("rnd", String.valueOf(new Date().getTime()));
            Utils.postrequest("https://api.live.bilibili.com/msg/send", header, data, "sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; bp_t_offset_619772228=405164167916667135; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; bp_video_offset_619772228=409109640839843003; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1593865247,1594123425,1594126827; _dfcaptcha=4e49477a3f2d5a826777c890fa718740; bfe_id=0dbdfb859ca0342fbea8373157bc809c; PVID=2");
            Thread.sleep(500);
        }

    }


    //直播间领辣条
    public static int lingLaTiao(int count) throws Exception {
        int i = count;
        while (count < (i + 300)) {
            Connection connect = Jsoup.connect("https://api.live.bilibili.com/xlive/lottery-interface/v3/guard/join");
            Map<String, String> header = new HashMap<String, String>();
            header.put("content-type", "application/x-www-form-urlencoded");
            header.put("origin", "https://live.bilibili.com");
            header.put("referer", "https://live.bilibili.com/");
            header.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
            connect.cookie("Cookie", "sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; bp_video_offset_619772228=409560225856138278; bp_t_offset_619772228=409560225856138278; dy_spec_agreed=1; _dfcaptcha=9f39d7e049325d77c131eb1012033587; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1594126827,1594185093,1594208333,1594259653; bfe_id=7b6a677b97d4786cd8b2f807c787d88b; bsource=share_source_qqchat; PVID=7");
            connect.data("roomid", "212332");
            connect.data("type", "guard");
            connect.data("csrf_token", "2d1cd64f8d95d254d3dc44077a7df701");
            connect.data("csrf", "2d1cd64f8d95d254d3dc44077a7df701");
            connect.data("id", String.valueOf(count));
            connect.headers(header);
            connect.ignoreContentType(true).post();
            count++;
            Thread.sleep(175);
        }
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\cookie\\vaildnumber.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(count);

        return count;
    }

    //发送关注的,只要提供uid,仅仅针对互动抽奖
    public static void BiliGuanzhu(String uid) throws Exception {
        Connection connect = Jsoup.connect("https://api.vc.bilibili.com/feed/v1/feed/SetUserFollow");
        Map<String, String> header = new HashMap<String, String>();
        header.put("content-type", "application/x-www-form-urlencoded");
        header.put("origin", " https://t.bilibili.com");
        header.put("referer", " https://t.bilibili.com/topic/name/%E4%BA%92%E5%8A%A8%E6%8A%BD%E5%A5%96/feed");
        header.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        connect.cookie("Cookie", "sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; bp_video_offset_619772228=409560225856138278; bp_t_offset_619772228=409560225856138278; dy_spec_agreed=1; _dfcaptcha=9f39d7e049325d77c131eb1012033587; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1594126827,1594185093,1594208333,1594259653; bfe_id=7b6a677b97d4786cd8b2f807c787d88b; bsource=share_source_qqchat; PVID=7");
        connect.data("type", "1");
        connect.data("csrf_token", "2d1cd64f8d95d254d3dc44077a7df701");
        connect.data("follow", uid);
        connect.headers(header);
        connect.ignoreContentType(true).post();
    }

    //抽奖区根据dynamicid发评论的,仅针对互动抽奖
    public static void biliChoujiangQuSendmessage(String dynamicId) throws IOException {
        //组织语言
        String[] strs = {"当分子", "666666", "奥利给,造他", "万一呢?", "嘿嘿", "无敌,好吧", "我就是我,不一样的烟火", "俺懂"};
        Random random = new Random();

        Connection connect = Jsoup.connect("https://api.bilibili.com/x/v2/reply/add");
        Map<String, String> header = new HashMap<String, String>();
        header.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        header.put("origin", "https://t.bilibili.com");
        header.put("referer", " https://t.bilibili.com/topic/name/%E4%BA%92%E5%8A%A8%E6%8A%BD%E5%A5%96/feed");
        header.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        connect.cookie("Cookie", "sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; bp_video_offset_619772228=409560225856138278; bp_t_offset_619772228=409560225856138278; dy_spec_agreed=1; _dfcaptcha=9f39d7e049325d77c131eb1012033587; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1594126827,1594185093,1594208333,1594259653; bfe_id=7b6a677b97d4786cd8b2f807c787d88b; bsource=share_source_qqchat; PVID=7");
        connect.data("type", "11");
        connect.data("oid", dynamicId);
        connect.data("message", strs[random.nextInt(strs.length - 1)]);
        connect.data("csrf", "2d1cd64f8d95d254d3dc44077a7df701");
        connect.data("plat", "1");
        connect.data("jsonp", "jsonp");
        connect.headers(header);
        connect.ignoreContentType(true).post();
    }

    //    抽奖区根据自己的uid和dynamicid转发的的,仅针对互动抽奖
    public static void biliChoujiangQuZhuanfa(String dynamicId) throws IOException {
        //组织语言
        String[] strs = {"当分子", "666666", "奥利给,造他", "万一呢?", "嘿嘿", "无敌,好吧", "我就是我,不一样的烟火", "俺懂"};
        Random random = new Random();

        Connection connect = Jsoup.connect("https://api.vc.bilibili.com/dynamic_repost/v1/dynamic_repost/reply");
        Map<String, String> header = new HashMap<String, String>();
        header.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        header.put("origin", "https://t.bilibili.com");
        header.put("referer", " https://t.bilibili.com/topic/name/%E4%BA%92%E5%8A%A8%E6%8A%BD%E5%A5%96/feed");
        header.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        connect.cookie("Cookie", "sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; bp_video_offset_619772228=409560225856138278; bp_t_offset_619772228=409560225856138278; dy_spec_agreed=1; _dfcaptcha=9f39d7e049325d77c131eb1012033587; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1594126827,1594185093,1594208333,1594259653; bfe_id=7b6a677b97d4786cd8b2f807c787d88b; bsource=share_source_qqchat; PVID=7");
        connect.data("type", "1");
        connect.data("rid", dynamicId);
        connect.data("uid", "619772228");
        connect.data("content", strs[random.nextInt(strs.length-1)]);
        connect.data("csrf_token", "2d1cd64f8d95d254d3dc44077a7df701");
        connect.data("extension", "{\"emoji_type\":1}");
        connect.data("from", "create.comment");
        connect.data("repost_code", "30000");
        connect.headers(header);
        connect.ignoreContentType(true).post();
    }

    //开启header
    @Test
    public void headertest() throws Exception {
        String k1 = " header.put";
        String s = "referer:https://t.bilibili.com/topic/name/%E4%BA%92%E5%8A%A8%E6%8A%BD%E5%A5%96/feed\n" +
                "origin:https://t.bilibili.com\n" +
                "cookie:l=v; sid=izrhxjpb; _uuid=9B1EBC53-24DE-3C3B-5478-C7B04BE21BFA39066infoc; buvid3=41EFFC96-BFEA-4264-96FE-6C4594B8888453923infoc; LIVE_BUVID=AUTO3115929677890054; bp_video_offset_221749181=404765698027349726; bp_t_offset_221749181=404766372336171715; CURRENT_FNVAL=16; rpdid=|(um~uYJJm)m0J'ulmJ|)Jm|Y; DedeUserID=619772228; DedeUserID__ckMd5=e9b2d53e131edb2b; SESSDATA=1d509e2c%2C1609413643%2Cb3f9e*71; bili_jct=2d1cd64f8d95d254d3dc44077a7df701; CURRENT_QUALITY=0; dy_spec_agreed=1; bsource=share_source_qqchat; bp_t_offset_619772228=409879715588495536; _dfcaptcha=3339c073f55cc0745758ed983d19b790; PVID=25; bp_video_offset_619772228=409934652517511129\n" +
                "content-type:application/x-www-form-urlencoded\n" +
                "user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36";
        Utils.getMap(k1, s);
    }

    //开启data
    @Test
    public void datatest() throws Exception {
        String k1 = "connect.data";
        String s = "oid:410287681648696972\n" +
                "type:17\n" +
                "message:666666\n" +
                "plat:1\n" +
                "jsonp:jsonp\n" +
                "csrf:2d1cd64f8d95d254d3dc44077a7df701";
        Utils.getMap(k1, s);
    }
}

